package com.example.mybatisplus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mybatisplus.mapper.KnrdMapper;
import com.example.mybatisplus.mapper.UserManageMapper;
import com.example.mybatisplus.model.domain.Knrd;
import com.example.mybatisplus.model.domain.WhitelistSetting;
import com.example.mybatisplus.mapper.WhitelistSettingMapper;
import com.example.mybatisplus.model.dto.PageDTO;
import com.example.mybatisplus.service.WhitelistSettingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 学校用户白名单设置 服务实现类
 * </p>
 *
 * @author sharplu
 * @since 2023-07-06
 */
@Service
public class WhitelistSettingServiceImpl extends ServiceImpl<WhitelistSettingMapper, WhitelistSetting> implements WhitelistSettingService {

    @Autowired
    private KnrdMapper knrdMapper;

    @Autowired
    private UserManageServiceImpl userManageService;

    @Override
    public WhitelistSetting login(WhitelistSetting whitelistSetting) {
        QueryWrapper<WhitelistSetting> wrapper = new QueryWrapper<>();
        wrapper.eq("sn",whitelistSetting.getSn()).eq("password",whitelistSetting.getPassword());
        WhitelistSetting one = baseMapper.selectOne(wrapper);
        // 为空有可能是学生第一次登录
        if(one == null){
            // 去困难认定表查一下
            QueryWrapper<Knrd> knrdQueryWrapper = new QueryWrapper<>();
            knrdQueryWrapper.eq("student_id",whitelistSetting.getSn());
            List<Knrd> knrds = knrdMapper.selectList(knrdQueryWrapper);// 绝对不会返回null，最多返回一个长度为0的集合
            if(knrds.size()>0){
                Knrd k = knrds.get(0);
                WhitelistSetting newUser = new WhitelistSetting().setName(k.getName())
                        .setPassword(k.getStudentId())
                        .setSn(k.getStudentId())
                        .setRoleId(1L);
                baseMapper.insert(newUser);
                one = newUser;
            }
        }
        return one;
    }

    @Override
    public Page<WhitelistSetting> pageList(PageDTO pageDTO, WhitelistSetting whitelistSetting) {
        QueryWrapper<WhitelistSetting> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(whitelistSetting.getSn())){
            wrapper.like("sn",whitelistSetting.getSn());
        }
        if(StringUtils.isNotBlank(whitelistSetting.getName())){
            wrapper.like("name",whitelistSetting.getName());
        }
        if(whitelistSetting.getRoleId()!=null){
            wrapper.eq("role_id",whitelistSetting.getRoleId());
        }
        Page<WhitelistSetting> page = new Page<>(pageDTO.getPageNo(),pageDTO.getPageSize());
        baseMapper.selectPage(page, wrapper);
        return page;
    }
}
